<template>
  <div v-if="dialogVisible" class="">
    <a-modal
      v-model:visible="dialogVisible"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :title="dialogTitle"
      :ok-loading="btnLoading"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <a-form ref="formRef" :model="formModel">
        <a-form-item
          field="name"
          label="名称"
          required
          :validate-trigger="['change', 'input']"
          :rules="[
            {
              required: true,
              message: '名称不能为空',
            },
          ]"
            label-col-flex="80px"
        >
          <a-input v-model="formModel.name" placeholder="请输入名称"/>
        </a-form-item>
        <a-form-item field="info" label="详细" label-col-flex="80px">
          <a-textarea v-model="formModel.info" allow-clear :max-length="{ length: 20, errorOnly: true }" show-word-limit/>
        </a-form-item>
        <a-form-item field="status" label="状态" label-col-flex="80px">
          <a-input-number v-model="formModel.status" :step="0.01" :precision="2" :min="1" :max="10" :style="{width:'100px'}"/>
        </a-form-item>
        <a-form-item field="sort" label="排序" label-col-flex="80px">
          <a-input-number v-model="formModel.sorting" mode="button" :style="{width:'160px'}"/>
        </a-form-item>
        <a-form-item field="user_name" label="用户" label-col-flex="80px">
          <a-input-group>
            <a-input v-model="formModel.user_name" placeholder="" :disabled="true" />
            <a-button type="text" @click="addUser">选择用户</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item field="district" label="地址" label-col-flex="80px">
          <a-cascader
            v-model="formModel.allRegion"
            :options="regionTreeDatas"
            expand-trigger="hover"
            :field-names="{ value: 'id', label: 'name' }"
            placeholder="请选择"
            path-mode
            allow-search
            allow-clear
            :format-label="regionFormat"
          >
          </a-cascader>
        </a-form-item>
        <a-form-item field="district" label="地址(懒加载)" label-col-flex="80px">
          <a-cascader
            v-model="formModel.lazyAllRegion"
            :options="lazyRegionTreeDatas"
            :load-more="loadMoreRegions"
            placeholder="请选择"
            path-mode
            allow-search
            allow-clear
          >
          </a-cascader>
        </a-form-item>
        <a-form-item field="latitude" label="" label-col-flex="80px">
          <a-input v-model="formModel.details" id="mapKeyword" placeholder="请输入请输入详细地址" />
        </a-form-item>
<!--        <a-form-item field="" label="" label-col-flex="80px">
          <AmapMap keyword-id="mapKeyword" :address-detail="{longitude: formModel.longitude, latitude: formModel.latitude}" @mapCallback="mapCallback"/>
        </a-form-item>-->
        <a-form-item field="" label="表单内容" label-col-flex="80px">
          <a-table
            row-key="id"
            :pagination="false"
            :data="formModel.form_content"
            :bordered="{ wrapper: true, cell: true }"
            :scroll="{ x: '100%', y: 'auto' }"
            :draggable="{ type: 'handle', width: 40 }"
            style="width: 100%"
          >
            <template #columns>
              <a-table-column title="字段名" align="center" :width="200">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.name`" label="" hide-label>
                    <a-input v-model="record.name" max-length="40" placeholder="40个字符内"/>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="类型" align="center" :width="180">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.type`" label="" hide-label>
                    <a-select v-model="record.type" placeholder="请选择">
                      <a-option v-for="(fieldType, fieldTypeKey) in formContent.fieldTypes" :key="fieldTypeKey" :value="fieldTypeKey" :label="fieldType" />
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="配置" align="center" :width="140">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.input_type`" label="" hide-label>
                    <a-select v-model="record.input_type" placeholder="请选择">
                      <a-option v-for="(inputType, inputTypeKey) in formContent.inputTypes" :key="inputTypeKey" :value="inputTypeKey" :label="inputType" />
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="选项值" align="center" :width="260">
                <template #cell="{ record, rowIndex }">
                  <a-form-item v-if="['2', '3'].includes(record.type)" :field="`form_content.${rowIndex}.option`" label="" hide-label>
                    <a-textarea v-model="record.option" max-length="200" placeholder="多个值以英文逗号分隔" allow-clear/>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="操作" align="center" :width="80">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="primary" status="danger" size="small" @click="delContent(record)"><icon-delete /></a-button>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-form-item>
        <a-form-item field="" label="" label-col-flex="80px">
          <a-button type="outline" long @click="addContent()">新增内容项</a-button>
        </a-form-item>

        <a-form-item field="" label="表单内容" label-col-flex="80px">
          <a-table
            row-key="id"
            :pagination="false"
            :data="formModel.form_content"
            :bordered="{ wrapper: true, cell: true }"
            :scroll="{ x: '100%', y: 'auto' }"
            :draggable="{ type: 'handle', width: 40 }"
            style="width: 100%"
          >
            <template #columns>
              <a-table-column title="操作" align="center" :width="80">
                <template #title>
                  <a-button type="primary" shape="circle" @click="addContent()">
                    <icon-plus />
                  </a-button>
                </template>
                <template #cell="{ record }">
                  <a-button v-if="formModel.form_content.length > 1" type="primary" status="danger" shape="circle" @click="delContent(record)"><icon-minus /></a-button>
                  <a-button v-else type="primary" status="danger" shape="circle" disabled><icon-minus /></a-button>
                </template>
              </a-table-column>
              <a-table-column title="字段名" align="center" :width="200">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.name`" label="" hide-label>
                    <a-input v-model="record.name" max-length="40" placeholder="40个字符内"/>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="类型" align="center" :width="180">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.type`" label="" hide-label>
                    <a-select v-model="record.type" placeholder="请选择">
                      <a-option v-for="(fieldType, fieldTypeKey) in formContent.fieldTypes" :key="fieldTypeKey" :value="fieldTypeKey" :label="fieldType" />
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="配置" align="center" :width="140">
                <template #cell="{ record, rowIndex }">
                  <a-form-item :field="`form_content.${rowIndex}.input_type`" label="" hide-label>
                    <a-select v-model="record.input_type" placeholder="请选择">
                      <a-option v-for="(inputType, inputTypeKey) in formContent.inputTypes" :key="inputTypeKey" :value="inputTypeKey" :label="inputType" />
                    </a-select>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="选项值" align="center" :width="260">
                <template #cell="{ record, rowIndex }">
                  <a-form-item v-if="['2', '3'].includes(record.type)" :field="`form_content.${rowIndex}.option`" label="" hide-label>
                    <a-textarea v-model="record.option" max-length="200" placeholder="多个值以英文逗号分隔" allow-clear/>
                  </a-form-item>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-form-item>
      </a-form>
<!--      <template #footer>
        <a-button size="small" @click="cancel">取消</a-button>
        <a-button type="primary" size="small" @click="submit">确定</a-button>
      </template>-->
    </a-modal>

    <SelectUser ref="selectUserRef" :ids="userId" selection-type="radio" @selectCallback="userCallback"/>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';

  import { useAdminStore } from '@/store';
  import { apiRegions } from '@/api/common';
  import { apiInfo, apiSave } from '@/api/test';
  import SelectUser from '@/views/components/select-user.vue';
  import AmapMap from '@/components/map/amap.vue';
  import cloneDeep from "lodash/cloneDeep";

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    id: {
      type: [Number, String],
      default: '',
    },
    statusList: {
      type: Array,
      default() {
        return [];
      },
    },
  });
  const emit = defineEmits(['saveCallback']);

  const adminStore = useAdminStore();
  const baseFormModel = () => {
    return {
      id: '',
      created_at: '',
      updated_at: '',
      name: '',
      info: '',
      sorting: 100,
      status: 1,

      user_id: '',
      user_name: '',

      province: '',
      province_id: '',
      city: '',
      city_id: '',
      district: '',
      district_id: '',
      details: '',
      latitude: '',
      longitude: '',
      allRegion: [['北京市', '直辖区', '东城区']],
      lazyAllRegion: [],

      form_content: [],
    };
  };
  const formRef = ref<FormInstance>();
  const formModel = ref<any>(baseFormModel());
  const modalStyle = {
    width: '70%',
    height: '60%',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };

  const dialogVisible = ref(false);
  const dialogTitle = ref();
  const btnLoading = ref(false);
  const selectUserRef = ref();
  const userId = ref();
  const regionTreeDatas = ref<any>([]);
  const lazyRegionTreeDatas = ref<any>([]);
  const specialRegions = ref<any>([]); // 香港、澳门 特殊地区

  const statusList = ref<any>([]);
  const formContent: any = {
    fieldTypes: {
      1: '单行文本',
      2: '单选',
      3: '多选',
      4: '省市区',
      5: '地图定位',
      6: '时间选择',
      7: '姓名+性别',
      8: '手机号',
    },
    inputTypes: {
      0: '不限',
      1: '数字',
    },
  };

  watch(
    [
      () => formModel.value.province_id,
      () => formModel.value.city_id,
      () => formModel.value.district_id,
    ],
    (
      [provinceId, cityId, districtId],
      [oldProvinceId, oldCityId, oldDistrictId]
    ) => {
      console.log('New', provinceId, cityId, districtId);
      console.log('Old', oldProvinceId, oldCityId, oldDistrictId);
    },
    { deep: true, immediate: true }
  );

  const getRegions = async () => {
    if (regionTreeDatas.value.length <= 0) {
      const { data } = await apiRegions();
      regionTreeDatas.value = data;
    }
  };
  const loadRegions = async (option?: any, done?: any) => {
    let where = {};
    let level = 3; // 层级
    if (option) {
      where = {
        parent_code: option.area_code,
      };
      // 香港、澳门只有3级
      if (option.label === '香港特别行政区' || option.label === '澳门特别行政区') {
        specialRegions.value.push(option.area_code);
      }
      if (option.level === 1 && specialRegions.value.includes(option.parent_code)) {
        level = 2;
      }
    } else {
      where = {
        level: 1,
      };
    }
    const { data } = await apiRegions(where);
    const nodes: any = [];
    data.forEach((item: any, index: number) => {
      nodes.push({
        value: item.name,
        label: item.name,
        isLeaf: item.level >= level,
        parent_code: item.parent_code,
        area_code: item.area_code,
        level: item.level,
      });
    });
    if (option) {
      done(nodes);
    } else {
      lazyRegionTreeDatas.value = nodes;
    }
  };
  const loadMoreRegions = async (option: any, done: any) => {
    await loadRegions(option, done);
  };
  // 地区格式化展示内容
  const regionFormat = (options: any[]) => {
    formModel.value.province = options[0].name;
    if (options[1]) {
      formModel.value.city = options[1].name;
    }
    if (options[2]) {
      formModel.value.district = options[2].name;
    }
    formModel.value.allRegion = [[formModel.value.province, formModel.value.city, formModel.value.district]];
    const labels = options.map(option => option.name);
    return labels.join(' / ');
  };
  // 表单重置
  const reset = async () => {
    // 表单重置
    formModel.value = baseFormModel();
    await formRef.value?.resetFields();
  };
  const fetchData = async (row?: any) => {
    statusList.value = props.statusList;

    getRegions();
    loadRegions();

    dialogVisible.value = true;
    dialogTitle.value = '新增';
    if (row) {
      dialogTitle.value = `编辑: ${row.id}`;
    }
    reset();
    if (row) {
      const { data } = await apiInfo({ id: row.id });
      formModel.value = data;
      // formModel.value.status = formModel.value.status.toString();
    }
  };
  // 提交
  const submit = async (done: any) => {
    btnLoading.value = true;
    try {
      const ruleRes = await formRef.value?.validate();
      // console.log(ruleRes);
      if (!ruleRes) {
        await apiSave(formModel.value);
        done();
        emit('saveCallback');
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
      btnLoading.value = false;
    } finally {
      done(false);
      btnLoading.value = false;
    }
  };

  // 选择用户
  const addUser = () => {
    userId.value = [formModel.value.user_id];
    selectUserRef.value.initData(userId.value);
  };
  // 选择用户回调
  const userCallback = (selected: any) => {
    console.log(selected);
    if (selected) {
      formModel.value.user_id = selected.id;
      formModel.value.user_name = selected.name;
    }
  };
  // 内容项
  const addContent = () => {
    formModel.value.form_content.push({
      id: formModel.value.form_content.length,
      name: '',
      field: '',
      input_type: '',
      option: '',
    });
  };
  const delContent = (row: any) => {
    const index = formModel.value.form_content.indexOf(row);
    if (index !== -1) {
      formModel.value.form_content.splice(index, 1);
    }
  };
  // 地图回调
  const mapCallback = (address: any) => {
    console.log(address);
  };

  const dialogCancel = () => {
    dialogVisible.value = false;
  };
  const dialogBeforeOk = (done: any) => {
    submit(done);
    // done();
    // done(false);
  };

  // 暴露方法【给父级调用】
  defineExpose({
    fetchData,
  });
</script>

<style scoped lang="less">
  .arco-table-container .arco-form-item {
    margin-bottom: 0;
  }
</style>